/*
 * Copyright (C) 2016 Lokiy(liulongke@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  　　　　http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.lokiy.databinding.adapter

import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import com.lokiy.core.adapter.BasicAdapter
import com.lokiy.databinding.BR

/**
 * DialDataBindingAdapter
 * lokiy
 * 2021-03-10
 */
class VMDataBindingAdapter<T> : BasicDataBindingAdapter<T> {
    private val viewModel: ViewModel?
    private val layoutId: Int

    constructor(viewModel: ViewModel?) : this({ }, viewModel)
    constructor(emptyData: EmptyData?, viewModel: ViewModel?) : super(emptyData, null) {
        this.viewModel = viewModel
        layoutId = 0
    }

    constructor(onLoadMoreListener: (BasicAdapter<T>.() -> Unit)?, viewModel: ViewModel?) : this(onLoadMoreListener, 0, viewModel)
    constructor(onLoadMoreListener: (BasicAdapter<T>.() -> Unit)?, layoutId: Int, viewModel: ViewModel?) : super(null, onLoadMoreListener) {
        this.viewModel = viewModel
        this.layoutId = layoutId
    }

    override fun getItemViewType1(position: Int): Int {
        val itemViewType1 = super.getItemViewType1(position)
        return if (itemViewType1 == 0) layoutId else itemViewType1
    }

    override fun onBindViewHolder(holder: Holder<T?>, position: Int) {
        val item = getItem(position) ?: return
        if (holder is BindingHolder<*>) {
            holder.getBinding<ViewDataBinding>().setVariable(BR.vm, viewModel)
            holder.getBinding<ViewDataBinding>().setVariable(BR.adapter, this)
        }
        holder.bindData(item)
    }
}